package com.cxl.bill.server.controller;

import com.cxl.bill.server.bean.ResponseBean;
import com.cxl.bill.server.db.bean.Bill;
import com.cxl.bill.server.service.BillService;
import com.cxl.bill.server.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RequestMapping("/bill")
@RestController
public class BillController {
    private final BillService billService;
    private final UserService userService;

    public BillController(BillService billService, UserService userService) {
        this.billService = billService;
        this.userService = userService;
    }

    @PostMapping("/add")
    public ResponseBean<?> add(
            @RequestParam("userId") Long userId,
            @RequestParam("amount") Double amount,
            @RequestParam(value = "explan", required = false) String explan,
            @RequestParam(value = "remark", required = false) String remark
    ) {
        if (userService.findById(userId) != null) {
            if (billService.insert(userId, amount, explan, remark)) {
                return ResponseBean.ok();
            } else {
                return ResponseBean.error("新增失败");
            }
        } else {
            return ResponseBean.error("该用户不存在");
        }
    }

    @PostMapping("/update")
    public ResponseBean<?> update(
            @RequestParam("id") Long id,
            @RequestParam("amount") Double amount,
            @RequestParam(value = "explan", required = false) String explan,
            @RequestParam(value = "remark", required = false) String remark
    ) {
        if (billService.findById(id) == null) {
            return ResponseBean.error("没有这个账单");
        } else {
            if (billService.update(id, amount, explan, remark)) {
                return ResponseBean.ok();
            } else {
                return ResponseBean.error("修改失败");
            }
        }
    }

    @PostMapping("/info")
    public ResponseBean<?> getBillInfoById(@RequestParam("id") Long id) {
        Bill dbBill = billService.findById(id);
        if (dbBill == null) {
            return ResponseBean.error("id错误");
        } else {
            return ResponseBean.ok(dbBill);
        }
    }

    /**
     * 根据用户Id查询账单列表
     * @param id 用户Id
     * @param page 页码
     * @param size 每页数量
     */
    @GetMapping("/list")
    public ResponseBean<?> listBillByUserId(
            @RequestParam("id") Long id,
            @RequestParam("page") int page,
            @RequestParam("size") int size) {
        PageHelper.startPage(page,size);
        Page<Bill> pageData = billService.listByUserId(id);
        return ResponseBean.ok(pageData.getResult(),pageData.getPageNum(),(int) pageData.getPages());
    }


}
